import {useCallback, useEffect, useLayoutEffect, useRef, useState} from 'react';
import {Icon, Text, TextInput, useAppTheme} from 'tsun-smart-ui';
import {useTranslation} from 'react-i18next';
import {
  Pressable,
  StyleSheet,
  TextInput as RNTextInput,
  View,
} from 'react-native';
import {stationApi} from '@/services/api/stationApi';
import {StationInstallerModel} from '@/services/api/stationApi';
import {FlashList} from '@shopify/flash-list';
import {useMMKVObject} from '@/hooks/useMMkv';
import userApi, {UserInfo} from '@/services/api/userApi';
import Toast from '@/utils/toast';
import {RouteProp, useNavigation, useRoute} from '@react-navigation/native';
import {StackNavigationProp} from '@react-navigation/stack';

function escapeRegExp(input: string): string {
  return input.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

const InstallerPicker = () => {
  const navigation = useNavigation<StackNavigationProp<any>>();
  const route = useRoute<RouteProp<any>>();
  const callbackRouteName = route?.params?.callbackRouteName;
  /// 只是为了选择安装商，不是为了更新安装商
  const justCameHereForSelectAnInstaller = Boolean(callbackRouteName);
  const theme = useAppTheme();
  const [search, setSearch] = useState('');
  const [installers, setInstallers] = useState<StationInstallerModel[]>([]);
  const [userInfo, setUserInfo] = useMMKVObject<
    UserInfo & {
      instName?: string;
      parentName?: string;
    }
  >('user_info');
  const instName =
    userInfo?.userType === 2 ? userInfo?.parentName : userInfo?.instName;
  const searchRef = useRef<RNTextInput>(null);
  const [loading, setLoading] = useState(false);
  const totalList = useRef<StationInstallerModel[]>([]);
  const [open, setOpen] = useState(false);
  const [selected, setSelected] = useState<StationInstallerModel | null>();
  const {t} = useTranslation();
  useLayoutEffect(() => {
    navigation.setOptions({
      headerRight: () => (
        <Text
          style={{
            color:
              selected || loading
                ? theme.colors?.brand?.primary
                : theme.colors?.brand?.primaryDisabled,
          }}
          disabled={!selected || loading}
          onPress={async () => {
            setLoading(true);
            if (callbackRouteName) {
              navigation.popTo(callbackRouteName, {
                installer: selected,
              });
              return;
            }
            userInfo?.userType! === 1
              ? await userApi.updateUserInfo({
                  instCode: selected?.code!,
                })
              : await userApi.updateParentInfo({
                  parentCode: selected?.code!,
                  code: userInfo?.instCode!,
                });
            Toast.success({
              message: t('userSetting.saveSuccess', {
                defaultValue: '保存成功',
              }),
            });
            const userInfoResponse = await userApi.getUserInfo();
            setUserInfo(userInfoResponse.data);
            navigation.goBack();
          }}>
          {t('common.confirmButtonText')}
        </Text>
      ),
    });
  }, [selected, loading]);
  useEffect(() => {
    stationApi.getStationInstallers().then(({data}) => {
      totalList.current = data;
    });
  }, []);
  const renderItem = useCallback(
    ({item, index}: {item: StationInstallerModel; index: number}) => {
      return (
        <Pressable
          className="   px-5"
          style={{
            backgroundColor: theme.colors?.neutral?.white,
            borderTopEndRadius: index === 0 ? 8 : 0,
            borderTopStartRadius: index === 0 ? 8 : 0,
            borderBottomEndRadius: index === installers.length - 1 ? 8 : 0,
            borderBottomStartRadius: index === installers.length - 1 ? 8 : 0,
          }}
          onPress={() => {
            setSelected(item);
            setSearch(item.name);
            setOpen(false);
            searchRef.current?.blur();
          }}>
          <View
            className="py-3 flex-row items-center justify-between"
            style={{
              borderBottomWidth:
                index === installers.length - 1 ? 0 : StyleSheet.hairlineWidth,
              borderBottomColor: theme.colors?.border?.primary,
              flex: 1,
            }}>
            {search ? (
              <Text>
                {item.name
                  .split(new RegExp(`(${escapeRegExp(search)})`, 'i'))
                  .map((part, index) =>
                    part.toLowerCase() === search.toLowerCase() ? (
                      <Text
                        key={index}
                        style={{color: theme.colors?.brand?.primary}}>
                        {part}
                      </Text>
                    ) : (
                      <Text key={index}>{part}</Text>
                    ),
                  )}
              </Text>
            ) : (
              <Text>{item.name}</Text>
            )}
            {/* {item.code === selected?.code && (
              <Icon
                name="check"
                size={16}
                color={theme.colors?.brand?.primary}
              />
            )} */}
          </View>
        </Pressable>
      );
    },
    [selected, installers],
  );

  const showChangeInstallerInfo = Boolean(
    instName && !justCameHereForSelectAnInstaller,
  );
  return (
    <View className="px-4 flex-1">
      {showChangeInstallerInfo && (
        <TextInput
          label={t('installer.current')}
          className="mt-3"
          readOnly
          value={instName}></TextInput>
      )}
      <TextInput
        className="mt-3"
        value={search}
        ref={searchRef}
        label={showChangeInstallerInfo ? t('installer.new') : ''}
        placeholder={t('common.search')}
        onFocus={() => {
          setOpen(true);
        }}
        onBlur={() => {
          if (search) {
            setInstallers(
              totalList.current.filter(item =>
                item.name.toLowerCase().includes(search.toLowerCase()),
              ),
            );
          } else {
            setSelected(null);
            setInstallers([]);
          }
        }}
        onChangeText={text => {
          setSearch(text);
          setSelected(null);
          if (text) {
            setInstallers(
              (totalList.current ?? [])?.filter(item =>
                item.name.toLowerCase().includes(text.toLowerCase()),
              ),
            );
          } else {
            setInstallers([]);
          }
        }}></TextInput>
      <View
        className="mt-2 max-h-[500] flex-1"
        style={{
          display: open ? 'flex' : 'none',
        }}>
        <FlashList
          keyboardShouldPersistTaps="handled"
          data={installers}
          showsVerticalScrollIndicator={false}
          renderItem={renderItem}
          keyExtractor={item => item.instId}></FlashList>
      </View>
    </View>
  );
};

export default InstallerPicker;
